package com.hmdp.utils;

import com.hmdp.entity.VoucherOrder;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class DeadLetterHandler {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "dlx.queue")
    public void handleDeadLetter(VoucherOrder voucherOrder,
                                 Message message,
                                 Channel channel,
                                 @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            // 获取重试次数
            int retryCount = (int) message.getMessageProperties()
                    .getHeaders()
                    .getOrDefault("x-retry-count", 0);

            if (retryCount < 3) {
                // 重新发送到主队列
                rabbitTemplate.convertAndSend("order.topic", "SeckillVoucher", voucherOrder, m -> {
                    m.getMessageProperties().setHeader("x-retry-count", retryCount + 1);
                    return m;
                });
            } else {
                log.error("订单处理最终失败，将写入失败记录: {}", voucherOrder);
                // 这里可以添加失败订单的处理逻辑
                channel.basicAck(deliveryTag, false);
            }
            


            
        } catch (Exception e) {
            log.error("处理死信消息异常: {}", e.getMessage());
            // 发生异常时，拒绝消息并重新入队
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
